local LuaMongo = _G.lua_mongo

local Grid = require("bag.Grid")
local Msg = require("core.Msg")
local Config = require("Config")
local Lang = require("common.Lang")
local ObjHuman = require("core.ObjHuman")
local CommonDB = require("common.CommonDB")
local MailManager = require("mail.MailManager")
local Broadcast = require("broadcast.Broadcast")
local RelationGiftExcel = require("excel.present").relationGift
local RoleLogic = require("role.RoleLogic")
local RoleDBLogic = require("role.RoleDBLogic")
local VipLogic = require("vip.VipLogic")
local DB = require("common.DB")
local BagLogic = require("bag.BagLogic")
local YunYingLogic = require("yunying.YunYingLogic")
local PanelDefine = require("broadcast.PanelDefine")
local CombatPosLogic = require("combat.CombatPosLogic")
local CombatDefine = require("combat.CombatDefine")

local RELATION_NUMMAX = 20
local RELATION_ZDL = 1  -- 战斗力判定
local RELATION_VIP = 2  -- VIP等级判定

-- 登陆检测关系玩家战力
local loginFileds = { combatHero = 1,heroBag = 1, vipLv = 1 }
function onLogin(human)
   
    local relationBind = human.db.relationBind
    if not relationBind then return end
    
    local relationRew = human.db.relationRew
    if not relationRew then return end
    
    for k, v in pairs(relationBind) do
        local bindHuman = ObjHuman.onlineUuid[k]
        if not bindHuman then
            local db = RoleDBLogic.getDb(k, loginFileds)
            bindHuman = { db = db }
        end
        if bindHuman.db then
           local zhandouli = CombatPosLogic.getCombatHeroZDL(bindHuman, CombatDefine.COMBAT_TYPE1)
           local vipLv = VipLogic.getVipLv(bindHuman)
           for i = 1, #RelationGiftExcel do 
              local config = RelationGiftExcel[i]
              local add = false
              if config.type == RELATION_ZDL and v.zhandouli[i] == nil then
                  if zhandouli >= config.counter then
                     add = true
                     v.zhandouli[i] = 1
                  end
              elseif config.type == RELATION_VIP and v.vip[i] == nil then
                  if vipLv >= config.counter then
                     add = true
                     v.vip[i] = 1
                  end
              end
           
              if add then
                 relationRew[i] = relationRew[i] or {} 
                 relationRew[i].maxCnt = relationRew[i].maxCnt or 0
                 relationRew[i].maxCnt = relationRew[i].maxCnt + 1
                 if relationRew[i].maxCnt >= config.cnt then
                    relationRew[i].maxCnt = config.cnt
                 end
              end
           end
        end
    end


end

-- 生成关系码
function relationCreate(human)
    -- 是否有唯一标识
    -- 生成十二位数唯一标识
    local firstStr = Config.SVR_INDEX
    local nowMax = CommonDB.getIdentityMax()
    local relation = string.format("%06d", nowMax)..""..firstStr
    human.db.relationKey = relation
end

-- 建立绑定关系
-- relationId   绑定码[目标]
-- relationBind 绑定队列
-- relationKey  推广码

local queryById = {relationKey = nil}
function relationBind(human, relationId)
    if human.db.relationId then 
        return Broadcast.sendErr(human, Lang.RELATIONGIFT_ERR_3) 
    end

    if relationId == "" then
        return
    end

    -- 查找唯一标识的玩家
    queryById.relationKey = relationId
    local data = {}
    LuaMongo.find(DB.db_char, queryById)
	if not LuaMongo.next(data) then
		return Broadcast.sendErr(human, Lang.RELATIONGIFT_ERR_1)
	end

     -- 检测玩家是否在线
    local bindHuman = ObjHuman.onlineUuid[data._id]
    local isOnline = true
    if not bindHuman then
        bindHuman = { db = data }
        isOnline = false
    end

    -- 检测自己是否绑定过
    if bindHuman.db.relationBind[human.db._id] then 
       return Broadcast.sendErr(human, Lang.RELATIONGIFT_ERR_3) 
    end
    
    -- 检测绑定数量
    local len = 0
    for k, v in pairs(bindHuman.db.relationBind) do
       len = len + 1
       if len >= RELATION_NUMMAX then
          return Broadcast.sendErr(human, Lang.RELATIONGIFT_ERR_2)
       end
    end

    -- 插入到绑定关系中
    human.db.relationId = relationId
    bindHuman.db.relationBind[human.db._id] = { vip={}, zhandouli={}}

    -- 离线玩家保存数据
    if not isOnline then
       ObjHuman.save(bindHuman)
    end

    return Broadcast.sendErr(human, Lang.RELATIONGIFT_SUCESS)
end

-- 关系奖励数据查询
-- 标识码
-- 奖励状态
-- 推荐的玩家列表
function relationQuery(human)

    local relationRew = human.db.relationRew
    local relationBind = human.db.relationBind
    
    local msgRet = Msg.gc.GC_RELATION_GIFT_QUERY
    msgRet.relationId = human.db.relationKey
    
    local len = 0
    for k, v in ipairs(RelationGiftExcel) do
       len = len + 1
       local net = msgRet.list[len]
       -- 奖励
       local rewardLen = #v.item
       for i = 1, rewardLen do
          local itemID = v.item[i][1]
          local itemCnt = v.item[i][2]
          Grid.makeItem(net.rewards[i], itemID, itemCnt)
       end
       net.id = k
       net.rewards[0] = rewardLen
       net.cnt = relationRew[k] and relationRew[k].maxCnt or 0   -- 可以领的次数
       net.cntMax = v.cnt                                        -- 最大领取次数
       net.getCht = relationRew[k] and relationRew[k].cnt or 0   -- 已经领取的次数
       net.type = v.type
       net.counter = v.counter
       net.txt = v.txt
    end
    msgRet.list[0] = len
    
    len = 0
    for k, v in pairs(relationBind) do
       len = len + 1
       local net = msgRet.roleList[len]
    
       local bReulst, human = RoleLogic.getRoleBaseByUuid(k, net.role)
       if human.db ~= nil then
          net.role.zhandouli = CombatPosLogic.getCombatHeroZDL(human, CombatDefine.COMBAT_TYPE1)
          net.vipLv = VipLogic.getVipLv(human)
       else
          relationBind[k] = nil
       end
    end
    msgRet.roleList[0] = len
    
    Msg.send(msgRet, human.fd)
end

-- 奖励领取
function relationRewardGet(human, id)
    local config = RelationGiftExcel[id]
    if not config then return end
    
    local relationRew = human.db.relationRew[id]
    if not relationRew then return end
    relationRew.cnt = relationRew.cnt or 0
    if relationRew.cnt >= config.cnt then
       return
    end
    if relationRew.maxCnt <= 0 then return end
    relationRew.cnt = relationRew.cnt + 1
    relationRew.maxCnt = relationRew.maxCnt - 1
    BagLogic.addItemList(human, config.item,"relationGift")
    
    -- 刷新页面
    relationQuery(human)
   
    
	for k, v in pairs(funcID) do
        YunYingLogic.updateIcon(YYInfo[k], human)
	    YunYingLogic.sendGroupUpdate(YYInfo[k], human, PanelDefine.PANEL_ID_3503)
        break
    end
end

function isRed(human)
    local relationBind = human.db.relationBind
    if not relationBind then return end
    
    local relationRew = human.db.relationRew
    if not relationRew then return end

    for i = 1, #RelationGiftExcel do 
        local config = RelationGiftExcel[i]
        if relationRew[i] and relationRew[i].maxCnt > 0 then
            return true
        end
    end 
end